// pages/userInfoCenter/index.js
const App = getApp();
const { Dialog, Toast } = require("../../../../../config/modal")
const utils = require("../../../../../utils/util")
const { LOGIN, LOCATION } = require("../../../../../config/login.js")
Page({
    /**
     * 页面的初始数据
     */
    data: {
        location_icon: '/static/img/school_location.png',
        title: "我找人帮忙",
        isAuth: App.$isAuth(),
        userIcon: '/static/img/student.png',
        adminIcon: '/static/img/official3.png',
        offsetTop: App.globalData.window.navHeight,
        window: App.globalData.window,
        theamTextColor: App.globalData.theamTextColor,
        loadMore: {
            show: false,
            type: "loading",
            text: "加载中..."
        },
        urgentState: {
            urgent: '紧急',
            normal: "正常",
            '紧急': "urgent",
            "正常": "normal",
        },
        // 用户和地址信息
        userInfo: {},
        tabActiveKey: 0,
        tabs: [
            {
                name: '待我同意',
                code: 'toAgree',
            }
            , {
                name: '待接单',
                code: 'no'
            }
            , {
                name: '进行中',
                code: 'doing',
            }
            , {
                name: '已完成',
                code: 'finish',
            }
            , {
                name: '已取消',
                code: 'cancel',
            }
            , {
                name: '超时未接单',
                code: 'timeout',
            }
        ],
        obj: {
            list: [],
            page: {
                pageNum: 1,
                pageSize: 15,
                pages: 0,
            }
        },
        userConcat: {
            show: false,
        },
        page: {
            one: 1,
        },
        searchParams: {
            taskStatus: "toAgree",
        }
    },
    URL: {
        taskList: "/task/myPushTask",
        checkAuth: "/customer/checkAuth",
        userConcatInfo: '/customer/userConcatInfo/?',
        agreeTask: "/task/agreeTask/?",
        disAgreeTask: "/task/disAgreeTask/?",
        finishTask: "/task/finishTask/?",
        delTaskByPushTaskNo: "/task/delMyPushTask/?",
        cancelTask: "/task/cancelTask/?",
    },
    page: {
        schoolPage: "/pages/school/index",
        userInfo: '/pages/tabbar/user/userInfoEdit/index',
        editPage: '/pages/tabbar/index/task/other/index',
        taskCenter: "/pages/tabbar/index/robOrders/index",
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        this.initAuthInfo();
        this.init(this.data.page.one, false)
        App.$on('authedCallback', this, (res) => {
            console.log("robOrders.js 接收授权成功事件消息");
        })
    },


    onShow() {

    }

    , toTaskCenter() {
        App.$redirectTo(this.page.taskCenter, false)
    }
    , initAuthInfo() {
        this.setData({
            'userInfo': App.$getUserInfo(),
        })
    }

    // 初始化数据
    , init(pageNum, loadMore) {
        let item = this.data.searchParams;

        let params = {};
        for (const itemKey in item) {
            params[itemKey] = item[itemKey];
        }
        params['pageNum'] = pageNum
        params['pageSize'] = this.data.obj.page.pageSize

        // 上拉到底的时候进行显示加载中
        this.setLoadingMore(loadMore, "loading", "加载中...")

        if (!loadMore ? true : loadMore) {
            // 弹出loading
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
        }

        App.$get(!loadMore ? true : loadMore, this.URL.taskList, params, res => {
            wx.stopPullDownRefresh();
            this.setData({
                "loadMore.show": false,
            })
            if (res.R) {
                let pageNum = 'obj.page.pageNum'
                let pageSize = 'obj.page.pageSize'
                let pages = 'obj.page.pages'
                this.setData({
                    [pageNum]: res.data.pageNum,
                    [pageSize]: res.data.pageSize,
                    [pages]: res.data.pages
                })

                let newData = res.data.rows;
                let sourceData = this.data.obj.list;
                if (!loadMore) {
                    sourceData = newData;
                } else {
                    // 上啦刷新，列表追加数据
                    newData.forEach(data => {
                        sourceData.push(data);
                    })
                }
                this.setData({
                    'obj.list': sourceData,
                })
            }

            if (!loadMore ? true : loadMore) {
                wx.hideLoading();
            }
        })
    },

    // tab栏切换
    onTypeChange(event) {
        let index = event.detail.index;
        this.setData({
            'searchParams.taskStatus': this.data.tabs[index].code,
        })
        this.setLoadingMore(false, "", "");
        this.init(this.data.page.one, false)
    }

    // 图片放大
    , showLagerImg(e) {
        let imgUrl = e.currentTarget.dataset.img;
        let imgUrls = [imgUrl];
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    }

    // 删除
    , deleteTask(e) {
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        if (e.detail === "right") {
            App.$delete(true, this.URL.delTaskByPushTaskNo.replace("?", item.taskNo), {}, res => {
                if (res.R) {
                    let list = this.data.obj.list;
                    list.splice(index, 1);
                    this.setData({
                        'obj.list': list
                    })
                }
            })
        } else if (e.detail === "left") {
            this.cancelTask(e);
        }
    }
    // 取消
    , cancelTask(e) {
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        if (item.taskStatus === 'cancel') {
            Toast("当前订单已取消")
            return;
        }
        App.$post(true, this.URL.cancelTask.replace("?", item.taskNo), {}, res => {
            if (res.R) {
                this.setData({
                    'tabActiveKey': 4,
                    'searchParams.taskStatus': this.data.tabs[4].code
                })
                let list = this.data.obj.list;
                list.splice(index, 1);
                this.setData({
                    'obj.list': list
                })
            }
        })
    }

    // 任务完成
    , finishTask(e) {
        let item = e.currentTarget.dataset.item;
        let _this = this;
        App.$alertConfirm({
            msg: "该同学 [" + item.receiveUser.realName + "] 是否完成了当前任务？",
            sureMsg: "是的",
            success() {
                App.$post(true, _this.URL.finishTask.replace("?", item.taskNo), {}, res => {
                    if (res.R) {
                        _this.setData({
                            'tabActiveKey': 3,
                            'searchParams.taskStatus': _this.data.tabs[3].code
                        })
                        _this.init(this.data.page.one, false)
                    }
                })
            }
        })
    }

    // 同意接单
    , toAgree(e) {
        let item = e.currentTarget.dataset.item
        let _this = this;
        App.$alertConfirm({
            msg: "您是否同意当前用户 [" + item.receiveUser.realName + "] 接您的任务？",
            sureMsg: "同意",
            success() {
                App.$post(true, _this.URL.agreeTask.replace("?", item.taskNo), {}, res => {
                    if (res.R) {
                        _this.setData({
                            'tabActiveKey': 2,
                            'searchParams.taskStatus': _this.data.tabs[2].code
                        })
                        _this.init(this.data.page.one, false)
                    }
                })
            }
        })
    }

    // 不同意接单
    , disAgreeTask(e) {
        let item = e.currentTarget.dataset.item
        let _this = this;
        App.$alertConfirm({
            msg: "您确定不同意当前用户 [" + item.receiveUser.realName + "] 接您的任务？",
            sureMsg: "不同意",
            success() {
                App.$post(true, _this.URL.disAgreeTask.replace("?", item.taskNo), {}, res => {
                    if (res.R) {
                        _this.setData({
                            'tabActiveKey': 1,
                            'searchParams.taskStatus': _this.data.tabs[1].code
                        })
                        _this.init(this.data.page.one, false)
                    }
                })
            }
        })
    }

    // 编辑
    , editTask(e) {
        let item = e.currentTarget.dataset.item
        let params = {
            id: item.id,
            content: item.content,
            taskNo: item.taskNo,
            schoolName: item.schoolName,
            effectivTime: item.effectivTime,
            urgentState: this.data.urgentState[item.urgentState],
            serviceFees: item.serviceFees,
            remark: item.remark,
        }
        App.$navigateTo(this.page.editPage + "?item=" + JSON.stringify(params))
    }

    , getUserConcat(e) {
        let userCode = e.currentTarget.dataset.user.userCode
        let userConcat = this.data.userConcat[userCode];
        if (utils.isInvalid(userConcat)) {
            App.$get(true, this.URL.userConcatInfo.replace("?", userCode), {}, res => {
                if (res.R) {
                    let userCodeKey = "userConcat." + userCode;
                    this.setData({
                        'userConcat.item': res.data,
                        [userCodeKey]: res.data
                    })
                    this.setData({
                        'userConcat.show': true
                    })
                }
            })
            return;
        }
        this.setData({
            'userConcat.item': userConcat,
        })
        this.setData({
            'userConcat.show': true
        })
    }

    , closeUserInfo() {
        this.setData({
            'userConcat.show': false
        })
    }
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    , onPullDownRefresh: function () {
        this.init(this.data.page.one, false);
    }

    , makePhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.userphone
        })
    }

    , copyWechat(e) {
        let wechat = e.currentTarget.dataset.wechat;
        wx.setClipboardData({
            data: wechat,
            success: function (res) {
                wx.getClipboardData({
                    success: function () {
                        wx.showToast({
                            title: '已复制',
                            icon: 'none'
                        })
                    }
                })
            }
        })
    }

    /**
     * 页面上拉触底事件的处理函数
     */
    , onReachBottom: function () {

        let page = this.data.obj.page;
        if (page.pages === 0 || page.pageNum + 1 > page.pages) {
            this.setLoadingMore(true, "end", "我是有底线的~")
            return;
        }
        this.init(page.pageNum + 1, true);
    }

    , setLoadingMore(show, type, text) {
        this.setData({
            "loadMore.show": show,
            "loadMore.type": type,
            "loadMore.text": text,
        })
    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        let url = '/pages/tabbar/index/robOrders/share/index';
        let item = null;
        if (e.from !== "menu") {
            item = e.target.dataset.detail
        }
        return App.$onShare(url, item, "任务分享");
    }
    ,
    scrollTop() {
        this.setScrollTop(0);
    },
    setScrollTop(val) {
        wx.pageScrollTo({
            scrollTop: val,
        })
    },

    showImgLager(e) {
        let imgUrl = e.currentTarget.dataset.img;
        let imgUrls = [imgUrl];
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    },

    // 页面滚动出发
    onPageScroll(options) {
        let flag = false;
        if (options.scrollTop > 200) {
            flag = true;
        }
        let key = 'obj.' + this.data.tabActiveKey + '.srcolltop'
        this.setData({
            [key]: options.scrollTop
        })
        this.setData({
            srcolltop: flag
        })
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

})
